package org.example;

import io.javalin.Javalin;
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebMain {

    private static Map<String, String> md5Cache = new ConcurrentHashMap<>();

    // RocksDB 相关
    private static final String DB_PATH = "rocksdb_md5"; // 数据库目录
    private static RocksDB db;

    static {
        RocksDB.loadLibrary();
        try {
            Options options = new Options().setCreateIfMissing(true);
            db = RocksDB.open(options, DB_PATH);
        } catch (RocksDBException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Javalin app = Javalin.create(config -> {
            config.staticFiles.add(staticFileConfig -> {
                staticFileConfig.hostedPath = "/";
                staticFileConfig.directory = "/public"; // 前端放 resources/public
            });
        }).start(9090);

        // MD5 加密接口
        app.post("/api/md5", ctx -> {
            String text = ctx.formParam("text");
            if (text == null) {
                ctx.status(400).result("Missing 'text' parameter");
                return;
            }
            String md5 = md5(text);

            // 保存到内存
            md5Cache.put(md5, text);

//            // 保存到 RocksDB
//            try {
//                db.put(md5.getBytes(StandardCharsets.UTF_8), text.getBytes(StandardCharsets.UTF_8));
//            } catch (RocksDBException e) {
//                e.printStackTrace();
//            }

            ctx.json(Map.of("md5", md5));
        });

        // “解密”接口
        app.post("/api/decode", ctx -> {
            String md5 = ctx.formParam("md5");
            if (md5 == null) {
                ctx.status(400).result("Missing 'md5' parameter");
                return;
            }

            // 先查内存
            String original = md5Cache.get(md5);

            // 如果内存没有，再查 RocksDB
            if (original == null) {
                try {
                    byte[] value = db.get(md5.getBytes(StandardCharsets.UTF_8));
                    if (value != null) {
                        original = new String(value, StandardCharsets.UTF_8);
                    }
                } catch (RocksDBException e) {
                    e.printStackTrace();
                }
            }

            if (original != null) {
                ctx.json(Map.of("text", original));
            } else {
                ctx.status(404).json(Map.of("error", "Not found"));
            }
        });
    }

    private static String md5(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(input.getBytes());
        BigInteger number = new BigInteger(1, digest);
        String hashText = number.toString(16);
        while (hashText.length() < 32) {
            hashText = "0" + hashText;
        }
        return hashText;
    }
}
